package com.lotter.api.aspect;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.lotter.common.util.StringUtil;
import com.lotter.invocation.StaticDataContext;


/**
 * 登录拦截器
 * @author zhangzechi
 *
 */
public class Loginterceptor extends HandlerInterceptorAdapter{

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	//拦截器
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//验证是否登录
	    String token = request.getParameter("token");
	    if(request.getRequestURI().indexOf("/website/testpay/pay")>-1) {//去掉支付宝测试支付url，不需要token验证
	    	return true;
	    }
	    if(request.getRequestURI().indexOf("/website/pay/alicalbk")>-1) {//去掉支付宝支付回调url，不需要token验证
 	    	return true;
 	    }
	    logger.info("token =" +token);
		if(StringUtil.isBlank(token)){
			logger.error("token 值没有获取到");
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter out = response.getWriter();  
        	Map<String,Object> result = new HashMap<String, Object>();
        	result.put("status", 403);
        	result.put("message", "token 值没有获取到");
			out.print(JSON.toJSONString(result));
			return false;
		}
		if(StaticDataContext.isExist(token)){
			return true;
		}else{
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter out = response.getWriter();  
        	Map<String,Object> result = new HashMap<String, Object>();
        	result.put("status", 403);
        	result.put("message", "token 已经过期你需要重新登录");
        	out.print(JSON.toJSONString(result));
			return false;
		}
	}
}
